package main

import (
	"flag"

	"github.com/astaxie/beego/logs"
)

func main() {
	var confFile string
	flag.StringVar(&confFile, "c", "", "config file")
	flag.Parse()

	// parse main config
	conf := ParseConfig(confFile)

	// parse listener config file
	// use separate file for dynamic update, for example add/delete listener
	listenerConfigs, err := ParseListenerConfig(conf.ListenerFile)
	if err != nil {
		panic(err)
	}

	// init global http route, for example apisix

	clientIDs := make([]string, 0)
	listenerMgr := NewListenerManager()
	sessionMgr := NewSessionManager()
	// listening ports
	for _, listenerConfig := range listenerConfigs {
		listener := NewListener(listenerConfig, sessionMgr)
		go func() {
			defer listener.Close()
			err := listener.ListenAndServe()
			if err != nil {
				logs.Error("listener %s serve fail: %v", listenerConfig.ID, err)
			}
		}()
		listenerMgr.AddListener(listenerConfig.ID, listener)
		clientIDs = append(clientIDs, listenerConfig.ClientID)
	}
	// init tunnel gateway server
	gw := NewGateway(conf.GatewayConfig, sessionMgr)
	gw.SetAvailableClientIDs(clientIDs)

	if conf.AutoReload {
		// watch listener file for add/delete listeners interval
		go WatchListenerFile(gw, conf.ListenerFile, listenerMgr, sessionMgr, listenerConfigs)
	}

	gw.ListenAndServe()
}
